<template>
  <el-dialog
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="50%"
    @close="editDialogClosed"
  >
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="70px"
    >
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUserInfo"> 确 定 </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getUserInfo, modifyUserInfo, getUserList } from 'network/user'

import { checkEmail, checkMobile } from 'common/rule'
export default {
  name: 'ModifyUser',
  data() {
    return {
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.$bus.$on('showEditDialog', async (id) => {
      this.editDialogVisible = true
      const res = await getUserInfo(id + '')
      if (res.meta.status !== 200)
        return this.$message.error('查询用户信息失败!')
      this.editForm = res.data
    })
  },
  methods: {
    showEditDialog() {
      this.$bus.$emit('showEditDialog')
    },
    editDialogClosed() {
      // 这个重置的是验证信息
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await modifyUserInfo(
          this.editForm.id,
          this.editForm.email,
          this.editForm.mobile
        )
        if (res.meta.status !== 200)
          return this.$message.error('更新用户信息失败')
        this.editDialogVisible = false
        this.$bus.$emit('getUserList')
        return this.$message.success('更新用户信息成功')
      })
    },
  },
}
</script>

<style>
</style>